package neo4j;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.index.Index;

public final class GraphDB {
	
	private static final String DB_PATH = "/Workties/database/workties.db";
	//private static final String DB_PATH = System.getProperty("user.dir")+"/Workties/database/workties.db";
	private static GraphDatabaseService graphDb;
	private static Index<Node> idIndex;
	
	private GraphDB(){
		GraphDB.graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
		GraphDB.idIndex = GraphDB.graphDb.index().forNodes("identifiers");
		registerShutdownHook(GraphDB.graphDb);
	}
	
	public static Index<Node> getIdIndex() {
		return GraphDB.idIndex;
	}

	//registerShutDownHook permet de fermer proprement la connexion a la BD mm en cas de crash de la JVM
	private static void registerShutdownHook( final GraphDatabaseService graphDb ){
		Runtime.getRuntime().addShutdownHook( new Thread(){
			@Override
			public void run(){
				graphDb.shutdown();
			}
		} );
	}

	public static GraphDatabaseService getGraphDb(){
		if (GraphDB.graphDb == null) {
			new GraphDB();
			System.out.println("Nouvelle Connexion : " +GraphDB.graphDb.toString());
		}
		return GraphDB.graphDb;	
	}
}
